package com.zh.config;

import com.alibaba.fastjson.JSON;
import com.zh.mapper.UserMapper;
import com.zh.pojo.User;
import com.zh.pojo.UserExample;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.thymeleaf.util.DateUtils;

import java.util.List;

//自定义的 Realm 需要集成 AUthoriziongRealm
//并 实现里面的两个方法
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了-->授权--> doGetAuthorizationInfo");
        //AuthorizationInfo 的实现类
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //设置用户的权限
        //info.setStringPermissions();

        //获取当前登录对象
        Subject subject =SecurityUtils.getSubject();
        User user =(User)subject.getPrincipal();
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了-->认证--> doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        //用户名，和密码 ，数据库中取
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(userToken.getUsername());
        List<User> users = userMapper.selectByExample(userExample);
        if(users.isEmpty()){
            return null;// 返回null, 会抛出UnknownAccountException 异常
        }

        //密码认证，shiro做
        //SimpleAuthenticationInfo 是AuthenticationInfo 的实现类
        //第一个参数传入 user对象，到授权哪里才可以获取到
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(users.get(0), users.get(0).getPassword(), "");
        return authenticationInfo;
    }

}
